﻿#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QFileDialog>
#include <QBuffer>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    QAudioFormat format;
    format.setSampleRate(16000);//声音采样频率
    format.setChannelCount(1);//单声道
    format.setSampleSize(16);//16位深
    format.setSampleType(QAudioFormat::SignedInt);
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setCodec("audio/pcm");

    recorder = new QAudioInput(format, this);
    player = new QAudioOutput(format, this);
    //声音播放完成后释放内存
    connect(player, &QAudioOutput::stateChanged, this, &Widget::play_state_slot);

    bds = new BaiduSpeech(this);
    connect(bds, &BaiduSpeech::doneASR, this, &Widget::asr_finished);
    connect(bds, &BaiduSpeech::doneTTS, this, &Widget::tts_finished);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_listenButton_toggled(bool checked)
{
    if (checked) {//开始录音
        ui->listenButton->setText("Stop");
        asrbuf = new QBuffer;
        asrbuf->open(QIODevice::ReadWrite);
        recorder->start(asrbuf);
    }
    else {//停止录音
        ui->listenButton->setText("Listen");
        recorder->stop();
        bds->setToken(ui->tkEdit->text());
        bds->doASR(asrbuf->data());
    }
}

void Widget::asr_finished(int error)
{
    Q_UNUSED(error);
    ui->textBrowser->setText(bds->text());
    asrbuf->deleteLater();
}

void Widget::on_speakButton_clicked()
{
    bds->setToken(ui->tkEdit->text());
    bds->doTTS(ui->textEdit->toPlainText());
}

void Widget::tts_finished(int error)
{
    if (error)
    {
        return;
    }
    ttsbuf = new QBuffer;
    ttsbuf->open(QIODevice::ReadWrite);
    ttsbuf->write(bds->audio());
    //从缓冲区头部开始播放
    ttsbuf->reset();

    player->start(ttsbuf);
}

void Widget::play_state_slot(QAudio::State s)
{
    if (s == QAudio::IdleState) {
        player->stop();
        ttsbuf->close();
        ttsbuf->deleteLater();
    }
}
